"""
用户账户相关功能：注册，短信，登陆，注销，找回密码
"""
from django.http import JsonResponse
from django.shortcuts import render, HttpResponse, redirect
from web.forms.account import RegisterModelForm, SendSMSForm, LoginSMSForm, LoginForm
from django.conf import settings
from web import models
import uuid
import datetime

""" 注册 """
def register(request):
    if request.method == 'GET':
        form = RegisterModelForm()
        return render(request, "web/register.html", {"form": form})

    print("POST")
    form = RegisterModelForm(data=request.POST)
    if form.is_valid():
        # 验证通过，写入数据库 (密码必须是密文)
        instance = form.save()
        # instance = models.UserInfo.objects.create(**form.cleaned_data)
        # 创建交易记录
        policy_object = models.PricePolicy.objects.filter(categoty=1, title='个人免费版').first()
        models.Transaction.objects.create(
            status=2,
            order=str(uuid.uuid4()),
            user=instance,
            price_policy=policy_object,
            count=0,
            price=0,
            start_datetime=datetime.datetime.now()
        )
        return JsonResponse({'status': True, 'data': '/login/'})
    # print(form.errors)
    return JsonResponse({'status': False, 'error': form.errors})

""" 发送短信 """
def send_sms(request):
    form = SendSMSForm(request, data=request.GET)
    # 只校验手机号：不能为空， 格式是否正确
    if form.is_valid():
        return JsonResponse({'status': True})

    print({'status': False, "error":form.errors})
    return JsonResponse({'status': False, "error":form.errors})

""" 短信登录 """
def login_sms(request):
    if request.method == "GET":
        form = LoginSMSForm()
        return render(request, 'web/login_sms.html', {'form': form})

    form = LoginSMSForm(request.POST)
    if form.is_valid():
        # 用户输入正确，登录成功
        user_object = form.cleaned_data['mobile_phone']
        # 将用户信息放入session中
        request.session['user_id'] = user_object.id
        request.session['user_name'] = user_object.username
        request.session.set_expiry(60 * 60 * 24 * 14)  # session过期时间设置为14天
        return JsonResponse({"status": True, 'data':"/index/"})
    return JsonResponse({"status": False, "error": form.errors})

""" 账号密码登录 """
def login(request):
    if request.method == "GET":
        form = LoginForm(request)
        return render(request, 'web/login.html', {'form': form})
    form = LoginForm(request, data=request.POST)
    if form.is_valid():
        username = form.cleaned_data.get('username')
        password = form.cleaned_data.get('password')

        # user_object = models.UserInfo.objects.filter(username=username, password=password).first()
        # (手机=username and pwd=pwd) or (邮箱=username and pwd=pwd)
        from django.db.models import Q
        user_object = models.UserInfo.objects.filter(Q(email=username) | Q(mobile_phone=username)).filter(password=password).first()
        if user_object:
            # 用户名密码正确 --> 跳转index主界面
            request.session['user_id'] = user_object.id
            request.session['user_name'] = user_object.username
            request.session.set_expiry(60*60*24*14) # session过期时间设置为14天
            return redirect('index')
        form.add_error('username', '用户名或密码错误')
    return render(request, 'web/login.html', {'form': form})

""" 生成图片验证码 """
def image_code(request):
    from io import BytesIO
    from utils.image_code import check_code

    image_object, code = check_code()

    # 将验证码保存到session中
    request.session['image_code'] = code.strip()
    request.session.set_expiry(60)  # 设置 session 60s 失效

    # 将验证码图片保存入内存中
    stream = BytesIO()
    image_object.save(stream, 'png')
    return HttpResponse(stream.getvalue())

""" 账户注销 """
def logout(request):
    request.session.flush()
    return redirect('index')